//
//  NetWorkBaseApi.swift
//  app
//
//  Created by g1 on 2023/7/15.
//

import UIKit
import Moya

enum NetWorkBaseApi {
    
    // 刷新token
    case refreshLoginToken(refreshToken: String) // 刷新token
    
    // 登录
    case register(params: [String: Any]) // 用户注册
    case accountLogin(params: [String: Any]) // 账号登录
    case authCodeLogin(params: [String: Any]) // 验证码登录
    case logout // 退出登录
    case resetPassword(params: [String: Any]) // 重置密码
    case destoryAccount // 注销账号
    case getSmsCode(params: [String: Any]) // 获取验证码
    
    // 首页
    case homeBanner // 景区banner
    case getScenicList(params: [String: Any]) // 获取景区列表
    case getScenicDetails(Int32) // 获取景区详情
    case getScenicStorys(params: [String: Any]) // 获取景区讲解和传奇故事
    case getHotCity // 获取热门城市
    case getChinaCitys(params: [String: Any]) // 获取国内城市列表
    case getForeignCitys(params: [String: Any]) // 获取海外城市列表
    case searchScenic(params: [String: Any]) // 根据关键词查找景区或者目的地
    case searchCity(params: [String: Any]) // 查询国内城市或者国外国家
    case collectScenic(params: [String: Any]) // 收藏景区
    case recordStoryNum(storyId: Int) // 故事记录
    
    // 收益
    case getIncomeRecord(params: [String: Any]) // 查询用户收益记录
    case withdrawWechat(params: [String: Any]) // 微信提现
    case bindWX(params: [String: Any]) // 绑定微信
    case getWithdrawPrices // 获取提现价格列表
    case unBindWX // 解绑微信
    case getAds(params: [String: Any]) // 获取广告位
    case getBalance // 获取余额
    
    // 内购
    case applePay(params: [String: Any]) // 苹果支付

    // 个人中心
    case getUserInfo // 获取用户信息
    case modefyNickname(params: [String: Any]) // 修改用户昵称
    case uploadAvatar(params: [String: Any]) // 修改用户头像
    case setInviteCode(params: [String: Any]) // 填写邀请码
    case receiveCoupon(couponId: Int) // 领取优惠券
    case getPurchaseHistory(params: [String: Any]) // 获取收藏记录
    case getCoupons(params: [String: Any]) // 获取优惠券
    case getUnUseCoupons(params: [String: Any]) // 获取未领取的优惠券
    case getCollects(params: [String: Any]) // 获取我的收藏
    case commitFeedback(params: [String: Any]) // 提交帮助反馈
    case getVipPriceList  // 获取会员价格表
    case setPassword(params: [String: Any]) // 设置密码
    case redemptionCode(redemptionCode: String) // 激活兑换码
    
    // 上传文件
    case updateFile(data: Data) // 上传文件
    
    // 升级
    case upgrade(params: [String: Any]) // 升级
    
    // 其他配置
    case redemptionSetting // 显示兑换
    
}

extension NetWorkBaseApi: TargetType {
    
    var baseURL: URL {
        switch self {
        default:
            return kApiEnvironmentManager.environmentStr
        }
    }
    ///不同接口的字路径
    var path: String {
        switch self {

        // 刷新token
        case .refreshLoginToken: // 刷新token
            return ""
            
        // 登录
        case .register:
            return "/api/user/regist" // 用户注册
        case .accountLogin:
            return "/api/user/login" // 账号登录
        case .authCodeLogin:
            return "/api/user/loginWithVerificationCode" // 验证码登录
        case .logout:
            return "/api/user/logout" // 退出登录
        case .resetPassword:
            return "/api/user/reset" // 重置密码
        case .destoryAccount:
            return "/api/user/unregister" // 注销账号
        case .getSmsCode:
            return "/api/common/smscode" // 获取验证码
            
        // 首页
        case .homeBanner:
            return "/api/rotation" // 首页banner
        case .getScenicList:
            return "/api/scenic" // 获取景区列表
        case .getScenicDetails(let scenicId):
            return "/api/scenic/\(scenicId)" // 获取景区详情
        case .getScenicStorys:
            return "/api/scenic/story" // 获取景区讲解和传奇故事
        case .getHotCity:
            return "/api/city/hotcity" // 获取热门城市
        case .getChinaCitys:
            return "/api/city/chinese/province" // 获取国内城市列表
        case .getForeignCitys:
            return "/api/city/foreign/country" // 获取海外城市列表
        case .searchScenic:
            return "/api/scenic/search" // 根据关键词查找景区或者目的地
        case .searchCity:
            return "/api/city" // 查询国内城市或者国外国家
        case .collectScenic:
            return "/api/scenic/collection" // 收藏景区
        case .recordStoryNum(let storyId):
            return "/api/usercenter/listener/\(storyId)" // 故事记录
            
        // 收益
        case .getIncomeRecord:
            return "/api/income/myincome" // 查询用户收益记录
        case .withdrawWechat:
            return "/api/income/withdrawal/weixin" // 微信提现
        case .bindWX:
            return "/api/income/bind/weixin4Ios" // 绑定微信
        case .unBindWX:
            return "/api/income/unbind" // 解绑微信
        case .getWithdrawPrices:
            return "/api/income/setting" // 获取提现价格列表
        case .getAds:
            return "/api/setting/ads" // 获取广告位
        case .getBalance:
            return "/api/income/balance" // 获取余额
            
        // 内购
        case .applePay:
            return "/api/apple/applePay" // 苹果支付
            
        // 个人中心
        case .getUserInfo:
            return "/api/user/userInfo" // 获取用户信息
        case .modefyNickname:
            return "/api/usercenter/nickname" // 修改用户昵称
        case .uploadAvatar:
            return "/api/usercenter/avatar" // 修改用户头像
        case .setInviteCode:
            return "/api/usercenter/fillInvitationCode" // 填写邀请码
        case .receiveCoupon(let couponId):
            return "/api/usercenter/coupons/\(couponId)" // 领取优惠券
        case .getPurchaseHistory:
            return "/api/usercenter/purchaseRecord" // 获取付款记录
        case .getCoupons:
            return "/api/usercenter/mycoupon" // 获取优惠券
        case .getUnUseCoupons:
            return "/api/usercenter/coupons" // 获取未领取的优惠券
        case .getCollects:
            return "/api/usercenter/mycollection" // 获取我的收藏
        case .commitFeedback:
            return "/api/feedback" // 提交帮助反馈
        case .getVipPriceList:
            return "/api/setting/applepurchase" // 获取会员价格表
        case .setPassword:
            return "/api/user/setPassword" // 设置密码
        case .redemptionCode:
            return "/api/usercenter/redemptionCode" // 激活兑换码
            
        // 上传文件
        case .updateFile:
            return "/api/common/file/upload" // 上传文件
            
        // 升级
        case .upgrade:
            return "/api/setting/versionUpdate" // 升级
            
        // 其他配置
        case .redemptionSetting:
            return "/api/usercenter/redemptionsetting" // 显示兑换
            
        }
        
    }
    /// 请求方式
    var method: Moya.Method {
        switch self {

        // 登录
        case .getSmsCode, .homeBanner:
            return .get
            
        // 首页
        case .getScenicList, .getScenicDetails, .getScenicStorys, .getHotCity, .getChinaCitys, .getForeignCitys, .searchScenic, .searchCity:
            return .get
            
        // 收益
        case .getIncomeRecord, .getWithdrawPrices, .getAds, .getBalance:
            return .get
        case .withdrawWechat, .bindWX, .unBindWX:
            return .put
            
        // 内购
        case .applePay:
            return .put
            
        // 个人中心
        case .modefyNickname, .uploadAvatar, .setInviteCode, .receiveCoupon, .destoryAccount, .resetPassword, .setPassword, .redemptionCode:
            return .put
        case .getUserInfo, .getPurchaseHistory, .getCoupons, .getCollects, .getUnUseCoupons, .getVipPriceList:
            return .get
            
        // 升级
        case .upgrade:
            return .get
            
        // 其他配置
        case .redemptionSetting:
            return .get
            
        default:
            return .post
        }
    }
    var sampleData: Data {
        //桩数据  如果有需要可以自己添加
        return Data()
    }
    
    var task: Task {
        
        var param = [String: Any]()

        switch self {
            
        // 登录
        case .getSmsCode(let params):
            param = param + params
            return .requestParameters(parameters: param, encoding: URLEncoding.default)
        case .accountLogin(let params), .authCodeLogin(let params), .register(let params):
            param = param + params
            return .requestParameters(parameters: param, encoding: JSONEncoding.default)
            
        // 首页
        case .homeBanner, .getHotCity:
            return .requestParameters(parameters: param, encoding: URLEncoding.default)
        case .getScenicDetails(let scenicId):
            param = param + ["scenicId": scenicId]
            return .requestParameters(parameters: param, encoding: URLEncoding.default)
            
        case .recordStoryNum(let storyId):
            param = param + ["storyId": storyId]
            return .requestParameters(parameters: param, encoding: URLEncoding.default)
        case .getScenicList(let params), .getScenicStorys(let params), .getChinaCitys(let params), .getForeignCitys(let params), .searchScenic(let params), .searchCity(let params):
            param = param + params
            return .requestParameters(parameters: param, encoding: URLEncoding.default)
        case .collectScenic(let params):
            param = param + params
            return .requestParameters(parameters: param, encoding: JSONEncoding.default)
            
            
        // 收益
        case .getWithdrawPrices, .unBindWX, .getBalance:
            return .requestParameters(parameters: param, encoding: URLEncoding.default)
        case .getIncomeRecord(let params), .getAds(let params):
            param = param + params
            return .requestParameters(parameters: param, encoding: URLEncoding.default)
        case .withdrawWechat(let params), .bindWX(let params):
            param = param + params
            var multipartFormData = [Moya.MultipartFormData]()
            for (key, value) in params {
                let data = "\(value)".data(using: .utf8) ?? Data()
                multipartFormData.append(MultipartFormData(provider: .data(data), name: key))
            }
            return .uploadMultipart(multipartFormData)
            
        // 内购
        case .applePay(let params):
            param = param + params
            return .requestParameters(parameters: param, encoding: URLEncoding.default)
            
        // 我的
        case .getUserInfo, .getVipPriceList, .destoryAccount:
            return .requestParameters(parameters: param, encoding: URLEncoding.default)
        case .receiveCoupon(let couponId):
            param = param + ["id": couponId]
            var multipartFormData = [Moya.MultipartFormData]()
            
            // 添加 Map 参数
            for (key, value) in param {
                let data = "\(value)".data(using: .utf8) ?? Data()
                multipartFormData.append(MultipartFormData(provider: .data(data), name: key))
            }

            return .uploadMultipart(multipartFormData)
        case .setInviteCode(let params), .uploadAvatar(let params), .modefyNickname(let params), .setPassword(let params):
            param = param + params
            var multipartFormData = [Moya.MultipartFormData]()
            
            // 添加 Map 参数
            for (key, value) in param {
                let data = "\(value)".data(using: .utf8) ?? Data()
                multipartFormData.append(MultipartFormData(provider: .data(data), name: key))
            }
            return .uploadMultipart(multipartFormData)
        case .updateFile(let data):
            let formData = MultipartFormData(provider: .data(data), name: "file", fileName: "file", mimeType: "image/jpeg")
            return .uploadCompositeMultipart([formData], urlParameters: param)
        case .getPurchaseHistory(let params), .getCoupons(let params), .getUnUseCoupons(let params), .getCollects(let params):
            param = param + params
            return .requestParameters(parameters: param, encoding: URLEncoding.default)
        case .commitFeedback(let params), .resetPassword(let params):
            param = param + params
            return .requestParameters(parameters: param, encoding: JSONEncoding.default)
        case .redemptionCode(let redemptionCode):
            param = param + ["redemptionCode": redemptionCode]
            var multipartFormData = [Moya.MultipartFormData]()
            
            // 添加 Map 参数
            for (key, value) in param {
                let data = "\(value)".data(using: .utf8) ?? Data()
                multipartFormData.append(MultipartFormData(provider: .data(data), name: key))
            }
            return .uploadMultipart(multipartFormData)
            
        // 升级
        case .upgrade(let params):
            param = param + params
            return .requestParameters(parameters: param, encoding: URLEncoding.default)
            
        // 其他
        case .redemptionSetting:
            return .requestParameters(parameters: param, encoding: URLEncoding.default)

        default:
            return .requestParameters(parameters:param, encoding: JSONEncoding.default)
        }
    }
    
    var headers: [String : String]? {
        
        var headerParam = [String: String]()
//        headerParam["Content-Language"] = "zh_CN"
        if kUserManager.isLogin {
            headerParam["token"] = kUserManager.accessToken
        }
        
        switch self {
        case .setInviteCode, .upgrade, .applePay:
            headerParam["Content-Type"] = "application/x-www-form-urlencoded"
        case .updateFile:
            headerParam["Content-Type"] = "multipart/form-data"
        default:
            headerParam["Content-Type"] = "application/json"
        }
        
        return headerParam

    }
}

 private extension NetWorkBaseApi {
   
    func getMIMETypeFromUploadFile(_ fileName: NSString) -> String {
        let fileExtensionName = fileName.pathExtension.lowercased()
        var fileType = ""
        if fileExtensionName == "jpg" || fileExtensionName == "jpeg" {
            fileType = "image/jpeg"
        }else if fileExtensionName == "gif" {
            fileType = "image/gif"
        }else if fileExtensionName == "png" {
            fileType = "image/png"
        }else if fileExtensionName == "mp3" {
            fileType = "audio/mp3"
        }else {
            fileType = "application/octet-stream"
        }
        return fileType
    }
}

extension Dictionary where Key == String, Value == Any {
    static func +(lhs: Dictionary, rhs: Dictionary) -> [String: Any] {
        var result: [String: Any] = [:]
        [lhs, rhs].forEach { (dict) in
            dict.forEach({ (k, v) in
                result.updateValue(v, forKey: k)
            })
        }
        return result
    }
}

enum NetworkErrorCode: Int {
    /// 微信登录解析失败，舍弃微信登录，启动手机号登录的逻辑
    case wxLoginParseError = 1004003011
    /// 没有绑定手机号
    case wxLoginBindMobleError = 1004003009
    /// 登录失败，账号被禁用
    case wxLoginAccountForbidden = 1004003001
    /// 用户没有登录
    case unLoginError = 1020000003
    /// 验证码已过期
    case authCodeExpireError = 1002014001
    /// 没有授权多多联盟
    case unAuthPddError = 1001
    /// 没有授权淘宝联盟
    case unAuthTbError = 1002
    /// 手机号绑定微信-该微信已经绑过账号
    case wxAuthAlreadyBindError = 1004001006
}
